#!/bin/bash

# YxYWeb 重启脚本
# 停止并重新启动服务

set -e  # 遇到错误立即退出

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 日志函数
log_info() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

log_success() {
    echo -e "${GREEN}[SUCCESS]${NC} $1"
}

log_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

log_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# 项目配置
PROJECT_NAME="YxYWeb"
PROJECT_DIR=$(dirname "$(readlink -f "$0")")

# 检查脚本是否存在
check_scripts() {
    if [ ! -f "$PROJECT_DIR/stop.sh" ]; then
        log_error "停止脚本不存在: $PROJECT_DIR/stop.sh"
        exit 1
    fi
    
    if [ ! -f "$PROJECT_DIR/start.sh" ]; then
        log_error "启动脚本不存在: $PROJECT_DIR/start.sh"
        exit 1
    fi
    
    # 设置脚本执行权限
    chmod +x "$PROJECT_DIR/stop.sh"
    chmod +x "$PROJECT_DIR/start.sh"
}

# 停止服务
stop_service() {
    log_info "停止 $PROJECT_NAME 服务..."
    
    if "$PROJECT_DIR/stop.sh" stop; then
        log_success "服务停止成功"
        return 0
    else
        log_warning "服务停止失败，尝试强制停止..."
        if "$PROJECT_DIR/stop.sh" force; then
            log_success "服务强制停止成功"
            return 0
        else
            log_error "无法停止服务"
            return 1
        fi
    fi
}

# 启动服务
start_service() {
    log_info "启动 $PROJECT_NAME 服务..."
    
    if "$PROJECT_DIR/start.sh" start; then
        log_success "服务启动成功"
        return 0
    else
        log_error "服务启动失败"
        return 1
    fi
}

# 等待服务就绪
wait_for_service() {
    local max_attempts=30
    local attempt=0
    local port=8000
    
    log_info "等待服务就绪..."
    
    while [ $attempt -lt $max_attempts ]; do
        if netstat -tuln 2>/dev/null | grep -q ":$port "; then
            log_success "服务已就绪"
            return 0
        fi
        
        attempt=$((attempt + 1))
        echo -n "."
        sleep 1
    done
    
    echo
    log_warning "服务启动超时，但可能仍在启动中"
    return 1
}

# 验证服务状态
verify_service() {
    local port=8000
    local health_url="http://localhost:$port/health"
    
    log_info "验证服务状态..."
    
    # 等待端口可用
    if ! wait_for_service; then
        log_warning "服务启动可能较慢，请稍后手动检查"
        return 1
    fi
    
    # 尝试健康检查
    if command -v curl > /dev/null 2>&1; then
        log_info "执行健康检查..."
        if curl -s -f "$health_url" > /dev/null 2>&1; then
            log_success "健康检查通过"
            return 0
        else
            log_warning "健康检查失败，但服务可能仍在启动中"
            return 1
        fi
    else
        log_info "curl未安装，跳过健康检查"
        return 0
    fi
}

# 显示服务信息
show_service_info() {
    echo
    echo "=========================================="
    log_success "$PROJECT_NAME 重启完成！"
    echo "=========================================="
    echo
    echo "服务信息:"
    echo "  地址: http://localhost:8000"
    echo "  健康检查: http://localhost:8000/health"
    echo "  日志文件: $PROJECT_DIR/logs/yxyweb.log"
    echo "  PID文件: $PROJECT_DIR/yxyweb.pid"
    echo
    echo "管理命令:"
    echo "  查看状态: $PROJECT_DIR/start.sh status"
    echo "  停止服务: $PROJECT_DIR/stop.sh"
    echo "  重启服务: $PROJECT_DIR/restart.sh"
    echo "  查看日志: tail -f $PROJECT_DIR/logs/yxyweb.log"
    echo
}

# 显示帮助信息
show_help() {
    echo "用法: $0 [选项]"
    echo
    echo "选项:"
    echo "  restart   重启服务 (默认)"
    echo "  force     强制重启服务"
    echo "  help      显示此帮助信息"
    echo
    echo "示例:"
    echo "  $0         # 正常重启服务"
    echo "  $0 restart # 正常重启服务"
    echo "  $0 force   # 强制重启服务"
}

# 主函数
main() {
    case "${1:-restart}" in
        "restart")
            echo "=========================================="
            echo "    重启 $PROJECT_NAME 服务"
            echo "=========================================="
            echo
            
            # 检查脚本
            check_scripts
            
            # 停止服务
            if stop_service; then
                log_info "等待服务完全停止..."
                sleep 2
            else
                log_error "停止服务失败，重启中止"
                exit 1
            fi
            
            # 启动服务
            if start_service; then
                # 验证服务
                verify_service
                show_service_info
            else
                log_error "启动服务失败"
                exit 1
            fi
            ;;
        "force")
            echo "=========================================="
            echo "    强制重启 $PROJECT_NAME 服务"
            echo "=========================================="
            echo
            
            # 检查脚本
            check_scripts
            
            # 强制停止服务
            log_info "强制停止服务..."
            if "$PROJECT_DIR/stop.sh" force; then
                log_success "服务强制停止成功"
            else
                log_warning "强制停止失败，继续启动新服务..."
            fi
            
            # 等待一段时间
            sleep 3
            
            # 启动服务
            if start_service; then
                # 验证服务
                verify_service
                show_service_info
            else
                log_error "启动服务失败"
                exit 1
            fi
            ;;
        "help"|"-h"|"--help")
            show_help
            ;;
        *)
            log_error "未知选项: $1"
            show_help
            exit 1
            ;;
    esac
}

# 执行主函数
main "$@"
